﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.ServiceModel;
using Caliburn.Micro;
using OI.DataServiceReference;
using OI.Framework;
using OI.ViewModels;
using Action = System.Action;

namespace OI.Async
{
    public class DataPackage : IResult
    {
        #region DATA

        public byte[] Results { get; set; }
        public Action Query { get; set; }
        public event EventHandler<ResultCompletionEventArgs> Completed;

        #endregion

        public DataPackage(DatasetDetailsOptionsPanelViewModel.Modes mode, string tableName)
        {
            var client = ServiceClients.CreateDataPackagingServiceClient();

            if (mode == DatasetDetailsOptionsPanelViewModel.Modes.Data)
            {
                client.CreateCSVCompleted += ClientCreateCSVCompleted;
                Query = () => client.CreateCSVAsync(tableName, client);
            }
            else if (mode == DatasetDetailsOptionsPanelViewModel.Modes.Map)
            {
                client.CreateShapefileCompleted += ClientCreateShapefileCompleted;
                Query = () => client.CreateShapefileAsync(tableName, client);
            }
        }

        #region IResult Members

        public void Execute(ActionExecutionContext context)
        {
            Query();
        }

        #endregion

        private void ClientCreateShapefileCompleted(object sender, CreateShapefileCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                IoC.Get<IShell>().HandleException(e.Error, "Error creating shapefile");
            }
            else if (!string.IsNullOrEmpty(e.Result.ErrorMessage))
            {
                IoC.Get<IShell>().HandleException(new Exception("Server error: " + e.Result.ErrorMessage),
                                                  "Error creating shapefile");
            }

            Results = e.Result.Data;
            ((DataPackagingServiceClient) e.UserState).CreateShapefileCompleted -= ClientCreateShapefileCompleted;
            Completed(this, new ResultCompletionEventArgs { Error = e.Error });
        }

        private void ClientCreateCSVCompleted(object sender, CreateCSVCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                IoC.Get<IShell>().HandleException(e.Error, "Error creating csv");
            }
            else if (!string.IsNullOrEmpty(e.Result.ErrorMessage))
            {
                IoC.Get<IShell>().HandleException(new Exception("Server error: " + e.Result.ErrorMessage),
                                                  "Error creating csv");
            }

            Results = e.Result.Data;
            ((DataPackagingServiceClient) e.UserState).CreateCSVCompleted -= ClientCreateCSVCompleted;
            Completed(this, new ResultCompletionEventArgs { Error = e.Error });
        }
    }
}